package com.hfdg.prototype.base.service.impl;

import com.github.pagehelper.PageInfo;

import com.hfdg.prototype.base.service.CommonsDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName CommonsDataServiceImpl
 * @Description TODO
 * @Author yuelh
 * @Date 2020-1-18 11:39
 * @Version 1.0
 * @Company 会飞的锅工作室
 **/
@Service
public class CommonsDataServiceImpl implements CommonsDataService {
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public List<Map<String, Object>> list(String sql, Map<String, Object> params) {
        StringBuilder baseSqlBuilder = new StringBuilder(sql);
        baseSqlBuilder.append("where 1 =1");
        if(null!=params&&0!=params.size()){
            for(String key:params.keySet()){
                baseSqlBuilder.append(" and "+key+"=:"+key+" ");
            }
        }
        return namedParameterJdbcTemplate.queryForList(sql,params);
    }

    @Override
    public PageInfo pageList(Integer offset, Integer limit, String sql, Map<String,Object> params) {
        StringBuilder baseSqlBuilder = new StringBuilder(sql);
        baseSqlBuilder.append("where 1 =1");
        if(null!=params&&0!=params.size()){
            for(String key:params.keySet()){
                baseSqlBuilder.append(" and "+key+"=:"+key+" ");
            }
        }
        String rowCountSql="select count(*) from ("+baseSqlBuilder.toString()+") rowCountsTable";
        Integer counts = namedParameterJdbcTemplate.queryForObject(rowCountSql.toString(),params,Integer.class);
        baseSqlBuilder.append(" limit "+offset+","+limit);
        List<Map<String,Object>> list = namedParameterJdbcTemplate.queryForList(baseSqlBuilder.toString(),params);
        PageInfo pageInfo = new PageInfo();
        pageInfo.setTotal(counts);
        pageInfo.setList(list);
        return pageInfo;
    }
}
